<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item :to="{path: '/'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item v-breadcrumb-certify></el-breadcrumb-item>
      <el-breadcrumb-item >
        <router-link class="rout" :to="{path: '/training/sale'}">销售管理</router-link>
      </el-breadcrumb-item>
      <el-breadcrumb-item>销售详情</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content">
      
      <el-row>
        <el-col :span="4">
          <e-heading style="margin-top:0" :grade="'1'">销售详情</e-heading>
        </el-col>
      </el-row>

      <div class="top-item clearfix" style="margin: 20px 0;">
        <div class="show-item">
            <ul>
              <li>{{train_sale_name}}</li>
            </ul>
            <p><span>{{'销售'}}</span></p>
        </div>
      </div>

      <el-row style="margin: 0 0 20px;">
        <el-col :span="16">
          <el-select size="small" clearable  v-model="studentState">
            <el-option v-for="item in stateOptions"
              :key="item.label"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <el-input style="width:263px;" placeholder="请输入姓名/地址/手机号" v-model.trim="query.searchKey" size="small"/>
          <el-button size="small" native-type="submit" type="primary-plain" @click="fetch">搜索</el-button> 
        </el-col>
      </el-row>

      <el-table ref="table" 
        :data="list.list"
        highlight-current-row>
        <el-table-column
          prop="name"
          label="姓名"
          width="80">
          <template slot-scope="scope">
            <p class="hidden">{{scope.row.name}}</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="sex"
          label="性别"
          width="60">
          <template slot-scope="scope">
            <span>{{scope.row.sex | sexFormat}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="parentMobile"
          label="手机号"
          width="100">
        </el-table-column>
        <el-table-column
          prop="address"
          label="住址"
          width="120">
          <template slot-scope="scope">
            <span class="hidden" :title="scope.row.address">{{scope.row.address}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="schoolName"
          label="咨询校区">
          <template slot-scope="scope">
            <span class="hidden" :title="scope.row.schoolName">{{scope.row.schoolName}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="source"
          label="来源"
          width="90">
          <template slot-scope="scope">
            <span>{{scope.row.origine | sourceEnum}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="studentStatus"
          label="学员状态"
          width="90">
          <template slot-scope="scope">
            <a @click="record(scope.row)"
              v-bind:class="{
              red: scope.row.studentStatus==1,
              green: scope.row.studentStatus==5,
              orange: scope.row.studentStatus==3
            }">{{scope.row.studentStatus | studentStatus}}</a>
          </template>
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-button class="link" type="text" size="mini" style="display:inline" @click="changeState(scope.row)">变更状态</el-button>
            <el-button class="link" style="margin-left:0;display:inline" type="text" size="mini" @click="showDialog(scope.row)">办理报名</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-bind="getPaginationProps(list)"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange">
      </el-pagination>
    </div>

    <!--办理报名-->
    <el-dialog
      :visible.sync="dialogVisible"
      title="办理报名"
      @close="resetForm()">
      <el-form ref="form" :model="form" :rules="rules" novalidate="novalidate" label-width="100px">
        
          <el-form-item
            prop="courseType"
            label="课程类型">
            <el-radio-group v-model="form.courseType"
             @change="handleTypeChange()">
              <el-radio :label="1">普通班</el-radio>
              <el-radio :label="2">次课</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <template v-if="form.courseType == 1">
            <el-form-item
              prop="courseId"
              label="课程"
              :rules="[{required: true, message: '请选择课程'}]">
              <el-select v-model="form.courseId"
                @change="getSchoolAndClass">
                <el-option v-for="item in normalCourseList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              prop="schoolId"
              label="校区"
              :rules="[{required: true, message: '请选择校区'}]">
              <el-select v-model="form.schoolId">
                <el-option v-for="item in schoolList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              prop="classType"
              label="班别"
              :rules="[{required: true, message: '请选择班别'}]">
              <el-select v-model="form.classType" 
                @change="getTimeClassList()">
                <el-option v-for="item in classTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              prop="pay"
              label="付款类型"
              :rules="[
                //{required: true, message: '请填写金额'},
                Object.assign({}, validator.rule.cannotBeZero, {courseType: form.courseType, timesCourseCode: form.timesCourseCode})
              ]">
              <InputPay  
                v-model.trim="form.pay" 
                :select-value.sync="form.payType"/>
            </el-form-item>
          </template>

          <template v-else>
            <el-form-item
              prop="courseId"
              label="课程"
              :rules="[{required: true, message: '请选择课程'}]">
              <el-select v-model="form.courseId"
                @change="getSchoolAndClass">
                <el-option v-for="item in timeCourseList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              prop="schoolId"
              label="校区"
              :rules="[{required: true, message: '请选择校区'}]">
              <el-select v-model="form.schoolId">
                <el-option v-for="item in schoolList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              prop="classType"
              label="班别"
              :rules="[{required: true, message: '请选择班别'}]">
              <el-select v-model="form.classType" 
                @change="getTimeClassList()">
                <el-option v-for="item in classTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              prop="timesCourseCode"
              label="次课"
              :rules="[{required: true, message: '请选择次课'}]">
              <el-select v-model="form.timesCourseCode">
                <el-option v-for="item in timeCourseOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              prop="pay"
              label="付款类型"
              :rules="[
                Object.assign({}, validator.rule.cannotBeZero, {courseType: form.courseType, timesCourseCode: form.timesCourseCode})
              ]">
              <InputPay  
                v-model.trim="form.pay" 
                :select-value.sync="form.payType"/>
            </el-form-item>
          </template>
        

        <div class="center" style="margin: 40px 0 20px;">
          <el-scrollbar wrap-class="sale-wrapper">
            <p v-for="item in SaleCollection"
              :key="item.courseName">
              <span>办理记录:{{new Date(item.createTime).format()}},</span>
              <span>金额:{{item.signupFee| formatMoney}},</span>
              <span>{{item.auditStatus | payStatus}},</span>
              <span>课程：{{item.courseName}}</span>
            </p>
          </el-scrollbar>
        </div>
        <div class="center">
          <el-button type="primary" @click="submit()">确认
          </el-button>
        </div>
      </el-form>
    </el-dialog>

    <!--变更状态-->
    <el-dialog
      :visible.sync="visible"
      title="变更状态">
      <div>
        <el-radio-group v-model="studentStatus">
          <el-radio :disabled="selectedItem.status == 3" :label="3">跟进中</el-radio>
          <el-radio :disabled="selectedItem.status == 4" :label="4">流失学员</el-radio>
        </el-radio-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleChangeStatus()">确认</el-button>
      </span>
    </el-dialog>

    <!--查看记录-->
    <el-dialog
      :title="title"
      class="sale-log-dialog"
      :visible.sync="logVisible">
      <el-row>
        <el-col :span="10" class="log-man">
          {{selectedItem.name}}
        </el-col>
      </el-row>
      <el-scrollbar wrap-class="sale-logs-wrapper">
        <ul class="log-items clearfix" v-if="title=='跟进中'">
          <li class="log-item relative" 
            v-for="item in followRecordList"
            :key="item.id">
            <div class="clearfix">
              <span class="fl">记录：</span>
              <span class="fr trial-time">{{new Date(item.updateTime).format()}}</span>
            </div>
            <p class="class-time">{{item.content}}</p>
          </li>
        </ul>

        <ul class="log-items clearfix" v-else>
          <li class="log-item relative" 
            v-for="item in trialRecordList"
            :key="item.id">
            <div class="clearfix">
              <span class="fl">试课信息：</span>
              <span class="fr trial-time">{{new Date(item.createTime).format()}}</span>
            </div>
            <p class="class-time">课程：<span>{{item.courseName}}</span></p>
            <div class="ab item-status">
              <el-button size="mini">{{item.trialStatus==0 ? '待试课' :'已试课'}}</el-button>
            </div>
          </li>
        </ul>
      </el-scrollbar>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="logVisible = false">关闭</el-button>
      </span>
    </el-dialog>

  </div>    
</template>
<script>
import validator from 'utils/validator'
import InputPay from '../../components/InputPay'
import {downloadFile, cloneObj, cikeExchange} from 'utils' // eslint-disable-line
import { pagingList } from 'utils/mixins'
import {mapGetters} from 'vuex'
import Api from 'api/train'
export default{
  mixins: [pagingList],
  components: {
    InputPay
  },
  created () {
    this.$store.dispatch('train_selectclass_list')
  },
  computed: {
    ...mapGetters({
      train_selectclass_list: 'train_selectclass_list',
      train_scholl_type_list: 'train_scholl_type_list', // 待选校区
      train_class_type_list: 'train_class_type_list', // 待选课程
      train_sale_name: 'train_sale_name',
      train_ck_course_list: 'train_ck_course_list' // 待选次课列表
    }),
    title () {
      return [1, 2].indexOf(this.selectedItem.studentStatus) > -1 ? '试课状态' : '跟进中'
    }
  },
  watch: {
    studentState () {
      if (typeof this.studentState === 'number') {
        this.query.statusList = [this.studentState]
      } else {
        this.query.statusList = [0, 1, 2, 3, 4, 5]
      }
    },
    // 课程列表
    train_selectclass_list () {
      if (this.train_selectclass_list) {
        this.train_selectclass_list.forEach(item => {
          if (item.properties === 0) {
            this.normalCourseList.push({
              label: item.courseName,
              value: item.id
            })
          } else if (item.properties === 2) {
            this.timeCourseList.push({
              label: item.courseName,
              value: item.id
            })
          }
        })
      }
    },
    // 校区列表
    train_scholl_type_list () {
      if (this.train_scholl_type_list) {
        this.schoolList = this.train_scholl_type_list.map(item => {
          return {
            label: item.value,
            value: item.key
          }
        })
      }
    },
    // 课程类型列表
    train_class_type_list () {
      if (this.train_class_type_list) {
        this.classTypeList = this.train_class_type_list.map(item => {
          return {
            label: item.value,
            value: item.key
          }
        })
      }
    },
    // 次课列表
    train_ck_course_list () {
      if (this.train_ck_course_list) {
        this.timeCourseOptions = cikeExchange(this.train_ck_course_list)
      }
    }
  },
  data () {
    let states = ['初始阶段', '试课阶段', '试课结束', '跟进中', '流失学员', '正式学员']
    let stateOptions = states.map((item, index) => {
      return {
        label: item,
        value: index
      }
    })
    return {
      studentState: '',
      validator,
      rules: {},
      visible: false,
      logVisible: false,
      dialogVisible: false,
      list: [],
      followRecordList: [],
      trialRecordList: [],
      stateOptions,
      query: Object.assign({}, this.getQuery(), {
        name: '', // 学员名称
        searchKey: '', // 关键字,
        statusList: [0, 1, 2, 3, 4, 5],
        userId: this.$route.query.userId
      }),
      form: {
        courseType: 1,
        schoolId: '', // 校区
        courseId: '', // 课程
        classType: '', // 班别
        timesCourseCode: '', // 次课
        payType: 1, // 付款类型
        pay: 0 // 实收
      },
      courseList: [],
      normalCourseList: [], // 课程列表
      timeCourseList: [], // 次课列表
      schoolList: [], // 校区列表
      classTypeList: [], // 班别列表
      studentStatus: 1,
      selectedItem: {},
      SaleCollection: [],
      timeCourseOptions: []
    }
  },
  methods: {
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let obj = cloneObj(this.form)
          Api.signUpFromSale({
            studentId: this.selectedItem.studentId,
            saleUserId: this.$route.query.userId,
            courseType: obj.courseType === 1 ? 'normal' : 'times',
            courseId: obj.courseId,
            schoolId: obj.schoolId,
            classesId: obj.classType,
            timesCourseCode: obj.timesCourseCode,
            payType: obj.payType,
            signupFee: obj.pay
          }).then((res) => {
            this.dialogVisible = false
            this.resetForm()
            this.fetch()
          })
        } else {
          return false
        }
      })
    },
    // 清除form所有字段
    resetForm () {
      this.$refs.form.resetFields()
    },
    showDialog (item) {
      this.selectedItem = item
      this.form.courseType = 1
      this.getSaleCollection(item)
    },
    // 查看跟进(试课)记录
    record (item) {
      this.selectedItem = item
      if (item.studentStatus === 1 || item.studentStatus === 2) { // 试课阶段或试课结束
        this.getTrialRecord(item.studentId)
      } else { // 跟进记录
        this.getFollowRecord(item.studentId)
      }
    },
    // 修改学员状态
    changeState (item) {
      this.selectedItem = item
      this.studentStatus = this.selectedItem.status === 3 ? 4 : 3
      this.visible = true
    },
    handleChangeStatus () {
      Api.changeStudentState({
        id: this.selectedItem.id,
        status: this.studentStatus
      }).then((res) => {
        this.fetch()
      })
      this.visible = !this.visible
    },
    fetch () {
      Api.getStudentList(this.query, {
        successMsg: 'none'
      }).then((res) => {
        this.list = res.data
      })
    },
    // 跟进记录
    getFollowRecord (id) {
      Api.getStuFollowRerordList({
        page: 1,
        rows: 10000,
        studentId: id
      }).then((res) => {
        this.followRecordList = res.data.list
        this.logVisible = true
      })
    },
    // 试课记录
    getTrialRecord (id) {
      Api.getStuTrialRecordList({
        page: 1,
        rows: 10000,
        studentId: id
      }).then((res) => {
        this.trialRecordList = res.data.list
        this.logVisible = true
      })
    },
    // 根据课程拉取 校区和班别信息
    getSchoolAndClass () {
      if (this.form.courseId) {
        this.$store.dispatch('train_scholl_type_list', {courseId: this.form.courseId})
        this.$store.dispatch('train_class_type_list', {courseId: this.form.courseId})
      }
    },
    // 获取销售人员列表
    getSaleCollection (item) {
      Api.saleCollection({
        studentId: item.studentId,
        saleUserId: this.$route.query.userId
      }).then((res) => {
        this.SaleCollection = res.data
        this.dialogVisible = true
      })
    },
    // 获取次课列表
    getTimeClassList () {
      if (this.form.courseType === 2) {
        this.$store.dispatch('train_ck_course_list', {
          courseId: this.form.courseId,
          classLevelId: this.form.classType // 班别Id
        })
      }
    },
    handleTypeChange () {
      this.form.courseId = ''
      this.form.schoolId = ''
      this.form.classType = ''
      this.form.timesCourseCode = ''
      this.schoolList = []
      this.classTypeList = []
    }
  }
}
</script>
<style lang="scss" scoped>

@import '~styles/sale.scss';
.red{
  color: #ff4949;
}
.green{
  color:$color-primary;
}
.orange{
  color: $color-warning;
}
.log-man{
  color: $color-primary;
  font-size:16px;
}
.log-items{
  margin: 20px 0;
  .log-item{
    border:1px solid #e3e3ec;
    width:331px;
    font-size:12px;
    float: left;
    margin:0 20px 10px 0;
    padding: 15px;
    border-radius: 3px;
    .class-time{
      margin: 8px 0;
    }
    .trial-time{
      color: #bbb;
    }
    .item-status{
      right: 15px;
      bottom: 15px;
    }
  }
}
.log-items .log-item:nth-child(2n){
  margin-right:0;
}
.fs20{
  font-size: 20px;
}
.rout{
  cursor: pointer;
  &:hover{
    color:$color-link
  }
}
</style>
<style lang="scss">
.sale-log-dialog{
  .el-dialog__header{
    border-bottom:1px solid #f0f0f0;
    padding-bottom:16px;
  }
  .el-dialog{
    width: 726px;
  }
  .el-dialog__body{
    padding:30px 20px;
  }
}
.sale-wrapper{
  max-height: 150px;
  overflow-y: scroll;
  p{
    font-size:12px;
    line-height: 16px;
    color: #999;
  }
}
.sale-logs-wrapper{
  max-height: 380px;
  overflow-y: scroll;
}
</style>
